package com.bishe.service.impl;

import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bishe.mapper.UserMapper;
import com.bishe.pojo.User;
import com.bishe.pojo.response.LoginInfo;
import com.bishe.pojo.response.UserInfo;
import com.bishe.service.UserService;
import com.bishe.util.LoginUtils;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public UserInfo login(LoginInfo loginInfo) {
        // 检查登录信息
        LoginUtils.checkLoginInfo(loginInfo);

        String userName = loginInfo.getUserName();
        String password = loginInfo.getPassword();

        // 登录用户查询
        User one = getOne(Wrappers.<User>lambdaQuery()
                .eq(User::getUserName, userName)
                .eq(User::getPassword, password),false);
        if (one == null) {
            return null;
        }

        StpUtil.login(one.getId(),new SaLoginModel()
                .setTimeout(60 * 30));

        UserInfo userInfo = new UserInfo();
        userInfo.setId(one.getId());
        userInfo.setName(one.getUserName());
        userInfo.setToken(StpUtil.getTokenValue());
        return userInfo;
    }
}
